package com.pz.gulimall.auth.schedule;

import com.pz.gulimall.auth.feign.ProductFeign;
import com.pz.gulimall.auth.service.ShopCarService;
import com.pz.gulimall.auth.vo.res.ShopCarItemResVo;
import com.pz.gulimall.common.exception.BizCodeEnum;
import com.pz.gulimall.common.exception.RRException;
import com.pz.gulimall.common.to.ShopCarItemTo;
import com.pz.gulimall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static com.pz.gulimall.auth.constan.CacheConstant.CART_CACHE_NAME;


@Slf4j
@Component
public class ShopCarSchedule {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeign productFeign;
    @Autowired
    private ShopCarService shopCarService;



    /**
     * 删除缓存，同步到数据库
     */
    @Scheduled(fixedRate = 12, timeUnit = TimeUnit.HOURS)
    @CacheEvict(value = CART_CACHE_NAME, allEntries = true)
    public void scheduled1_syncCartCacheToDB() {
        log.info("=====>>>>>同步购物项到数据库~~~~~~");
        log.info("开始同步> > > > >");
        // 1、取值
        // 1.1、获取购物项所有的 key
        Set<String> keys = redisTemplate.keys("CACHE_AUTH_SHOPCAR::*");
        List<String> loginIds = new ArrayList<>();
        List<ShopCarItemTo> datas = new ArrayList<>();
        if(keys!= null && !keys.isEmpty()){
            keys.forEach(key->{
                key = key.split("::")[1];
                loginIds.add(key);
            });
        }
        //1.2从缓存中获取数据
        if(!loginIds.isEmpty()){
            loginIds.forEach(loginId -> {
                List<ShopCarItemResVo> fromCache = shopCarService.getFromCache(loginId);
                if(!fromCache.isEmpty()){
                    for (ShopCarItemResVo cartItem : fromCache) {
                        cartItem.setTotalPrice();
                        ShopCarItemTo shopCarItemTo = new ShopCarItemTo();
                        BeanUtils.copyProperties(cartItem, shopCarItemTo);
                        String saleAttrs = "";
                        for (int i = 0; i < cartItem.getSaleAttrs().size(); i++) {
                            saleAttrs+= cartItem.getSaleAttrs().get(i);
                            if(i<cartItem.getSaleAttrs().size()-1){
                                saleAttrs+=";";
                            }
                        }
                        shopCarItemTo.setSaleAttrs(saleAttrs);
                        datas.add(shopCarItemTo);
                    }
                }
            });
        }

        log.info("要同步的数据，{}", datas);
        if(!datas.isEmpty()){
            try {
                R ans = productFeign.save(datas);
                if(ans.getCode() == 0){
                    log.info("购物项缓存数据同步成功！");
                }else {
                    log.error("购物项缓存数据同步失败---{}",ans.getMsg());
                }
            } catch (Exception e) {
                throw new RRException(BizCodeEnum.AUTH_RPC_PRODUCT_FAILED.getMsg(), BizCodeEnum.AUTH_RPC_PRODUCT_FAILED.getCode());
            }
        }

    }
}
